import sys
import json
import logging
from aistudentpack_complete import AIStudentPackAutomation

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('automation.log'),
        logging.StreamHandler(sys.stdout)
    ]
)


def load_config(config_file='config.json'):
    try:
        with open(config_file, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"Config file {config_file} not found. Please create it from config.example.json")
        sys.exit(1)


def main():
    config = load_config()
    
    token = config['5sim']['token']
    xsrf = config['5sim'].get('xsrf_token')
    target = config['automation']['target_accounts']
    workers = config['automation']['email_workers']
    timeout = config['automation']['max_runtime_seconds']
    output = config['output']['results_file']
    
    print("=== AI Student Pack Automation ===")
    print(f"Target accounts: {target}")
    print(f"Email workers: {workers}")
    print(f"Max runtime: {timeout} seconds")
    print(f"Output file: {output}")
    print("="*40)
    
    automation = AIStudentPackAutomation(token, xsrf)
    
    try:
        automation.run(target_accounts=target, max_time=timeout, num_email_workers=workers)
        
    except KeyboardInterrupt:
        print("\n⚠️ Interrupted by user")
    except Exception as e:
        print(f"❌ Error: {e}")
        logging.exception("Automation error")
    finally:
        automation.save_results(output)
        
        print("\n=== Summary ===")
        print(f"Accounts created: {len(automation.results)}")
        
        if automation.results:
            print("\nAccount Details:")
            for i, acc in enumerate(automation.results, 1):
                print(f"\n{i}. Email: {acc.email}")
                print(f"   Phone: {acc.phone_number}")
                print(f"   v0 Code: {acc.v0_code}")
                print(f"   ElevenLabs: {acc.elevenlabs_code}")
        
        print(f"\nResults saved to: {output}")


if __name__ == "__main__":
    main()